//
//  Search.m
//  testProj
//
//  Created by Laurent on 05/07/11.
//  Copyright 2011 Epita. All rights reserved.
//

#import "Search.h"
#import "MTISqliteManager.h"
#import "MyAnnotation.h"

@implementation Search

@synthesize mapViewPerso, dept;

- (void)mapViewDidFailLoadingMap:(MKMapView *)mapView withError:(NSError *)error
{
    
}

- (void)setCenterCoordinate:(CLLocationCoordinate2D)coordinate animated:(BOOL)animated
{
    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    MTISqliteManager *mng = [MTISqliteManager sharedInstance];
    [mng openDatabase];
    
    if (self.dept != @"-42")
    {        
        int temp = [self.dept intValue];

        MKCoordinateSpan span;
        span.latitudeDelta = 10;
        span.longitudeDelta = 10;
        
        double longi = 46.227638;
        double lati = 2.213749;
        
        CLLocationCoordinate2D coordForce;
        coordForce.latitude = longi;
        coordForce.longitude = lati;
        
        MKCoordinateRegion coordRegion;
        coordRegion.span = span;
        coordRegion.center = coordForce;
        
        [mapViewPerso setRegion:coordRegion animated:TRUE]; // Centrage de la carte sur la France

//        NSString *str = [NSString stringWithFormat:@"SELECT * FROM dechet WHERE codepostal LIKE ?", temp];
        
        NSString *str = @"SELECT * FROM dechet WHERE codepostal LIKE ?";
        sqlite3_stmt *stm2 = [mng compileQueryOrGetFromCache:str];
        NSString *maRecherche = [NSString stringWithFormat:@"%i___", temp];
        sqlite3_bind_text(stm2, 1, [maRecherche UTF8String], -1, SQLITE_STATIC);
        
        NSMutableArray *array = [NSMutableArray arrayWithObjects:nil];
        while (sqlite3_step(stm2) == SQLITE_ROW)
        {
            double longi2 = sqlite3_column_double(stm2, 4);
            double lati2 = sqlite3_column_double(stm2, 5);
            
            CLLocationCoordinate2D coordForce2;
            coordForce2.latitude = longi2;
            coordForce2.longitude = lati2; 
            MyAnnotation *annot = [[MyAnnotation alloc] initWithCoordinate:coordForce2];
            annot = [[MyAnnotation alloc] initWithCoordinate:coordForce2]; 
            [annot setTitle:@"Dechetterie"];            
            [array addObject:annot]; // On prepare la liste d'annotations
            [annot release];            
        }
        [mapViewPerso addAnnotations:array];
    }
    else
    {
    // Do any additional setup after loading the view from its nib.
    MKCoordinateSpan span;
    span.latitudeDelta = 2.5;
    span.longitudeDelta = 2.5;
       
    
    /*NSString *str = @"SELECT * FROM dechet WHERE id=42";
    sqlite3_stmt *stm = [mng compileQueryOrGetFromCache:str];    
    
    sqlite3_step(stm);*/
    
    double longi; //= sqlite3_column_double(stm, 4);
    double lati; //= sqlite3_column_double(stm, 5);
    
    /*longi = 48.858391; Paris
    lati = 2.35279;*/
    longi = 47.218371;
    lati = -1.553621;
    
    CLLocationCoordinate2D coordForce;
    coordForce.latitude = longi;
    coordForce.longitude = lati;
        
    MKCoordinateRegion coordRegion;
    coordRegion.span = span;
    coordRegion.center = coordForce;
    
    [mapViewPerso setRegion:coordRegion animated:TRUE]; // Centrage de la carte sur la position de la personne
    
    MyAnnotation *annot = [[MyAnnotation alloc] initWithCoordinate:coordForce]; // Annotation associee
    [annot setTitle:@"Votre position"];
    
    NSMutableArray *array = [NSMutableArray arrayWithObjects:annot, nil];
    [annot release];
    
    
    NSString *str2 = @"SELECT * FROM dechet"; // Recuperation de toutes les dechetteries
    
    sqlite3_stmt *stm2 = [mng compileQueryOrGetFromCache:str2];
    
    MyAnnotation *nearestAnnot = [[MyAnnotation alloc] initWithCoordinate:coordForce]; // Annotation de la dechetterie la plus proche
    double nearestdist = 9999.9;
    
    while (sqlite3_step(stm2) == SQLITE_ROW)
    {
        //char *ville = (char *)sqlite3_column_text(stm2, 1);
        double longi2 = sqlite3_column_double(stm2, 4);
        double lati2 = sqlite3_column_double(stm2, 5);
    
        CLLocationCoordinate2D coordForce2;
        coordForce2.latitude = longi2;
        coordForce2.longitude = lati2;
        // calcul de distance
        double cosi = cos(lati * M_PI / 180) * cos(lati2 * M_PI / 180) * (cos(longi * M_PI / 180) * cos(longi2 * M_PI / 180) + sin(longi * M_PI / 180) * sin(longi2 * M_PI / 180)) +  sin(lati * M_PI / 180) * sin(lati2 * M_PI / 180);
        double dist = 6378 * acos(cosi);
        
        // On ecarte les dechetteries qui sont trop loin (en pratique il aurait peut-etre ete plus indique de faire cela dans le select)
        if ((fabs(longi2 - longi) > 1) || (fabs(lati2 - lati) > 1))
            continue;
        else
        {
            annot = [[MyAnnotation alloc] initWithCoordinate:coordForce2]; 
            [annot setTitle:@"Autre Dechetterie"];
            // On met de cote la dechetterie la plus proche
            if (dist < nearestdist)
            {
                nearestAnnot = annot;
                nearestdist = dist;
            }
            [array addObject:annot]; // On prepare la liste d'annotations
            [annot release];
        }
    }
    sqlite3_finalize(stm2);
    
    [nearestAnnot setTitle:@"La plus proche"];
    [mapViewPerso addAnnotation:nearestAnnot];
    
    // Comme la plus proche est aussi dans la liste, on l'ajoute d'abord
    
    [mapViewPerso addAnnotations:array];
        
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (MKAnnotationView *) mapView:(MKMapView *) curentMapView viewForAnnotation:(id <MKAnnotation>) annotation
{
    /*if (annotation == mapViewPerso.userLocation) 
        return nil;*/
        if ([annotation title] == @"Votre position")
        {
            if ([curentMapView dequeueReusableAnnotationViewWithIdentifier:@"Votre position"] == nil) 
            {
                MKPinAnnotationView *av = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"Votre position"];                      
                [av setPinColor:MKPinAnnotationColorGreen];
                av.canShowCallout = YES;
                return av;
            }
        }
        if ([annotation title] == @"La plus proche")
        {
            if ([curentMapView dequeueReusableAnnotationViewWithIdentifier:@"La plus proche"] == nil) 
            {
                MKPinAnnotationView *av = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"La plus proche"];      
                [av setPinColor:MKPinAnnotationColorPurple];
                av.canShowCallout = YES;
                return av;
            }
        }
        MKPinAnnotationView *av = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"Dechetterie"];         
        [av setPinColor:MKPinAnnotationColorRed];
        av.canShowCallout = YES;
        return av;
}

@end
